import React, { PureComponent } from 'react'
import { connect } from "react-redux";
import dayjs from "dayjs";
import notify from "@utils/tip";
import { Select, Tabs, Button } from 'antd'
import DoubleCheck from "@common/presentational/DoubleCheck";
import { withRouter } from "react-router-dom";
import { getQuery, handleQueryEqual, setQuery } from "@utils/setUrlQuery";
import { WarehouseSelect } from '@components/warehouse/WarehouseSelect'
import CustomizeTableProvide, {
    CustomizeOrderTable,
    CustomizeTablePagination
} from "@common/presentational/CustomizeTable";
import {
    WAREHOUSE_ORDER_STATUS,
    WAREHOUSE_ORDER_STATUS_LIST
} from "@constants/WarehouseOrderStatus";
import { 
    getWarehouseOrderProcess,
    creatWarehouseOrderReady,
    creatWarehouseOrderMiss,
    creatWarehouseOrderPickUp,
    getWarehouseOrderInfo
} from "@sagas/warehouse/send";
import DateRangePicker from "@common/presentational/DateRangePicker";
import ParamsInput from "@common/presentational/ParamsInput";
import OrderDeliverModal from "@components/warehouse/modal/OrderDeliverModal";
import DeliverOrderDetailModal from "@components/warehouse/modal/DeliverOrderDetailModal";
import {priceFenToYuan} from "@utils/priceConversion";

@connect(({ warehouseManagement, send }) => ({
    processOrderListMap: send.processOrderListMap,
    selectedWarehouse: warehouseManagement.selectedWarehouse
}), {
    getWarehouseOrderProcess,
    creatWarehouseOrderReady,
    creatWarehouseOrderMiss,
    creatWarehouseOrderPickUp,
    getWarehouseOrderInfo
})
@withRouter
class WarehouseOrderPage extends PureComponent {
    constructor(props) {
        super(props);
        const {
            startDate = dayjs().subtract(1, 'month').add(1, 'days').format('YYYY-MM-DD'),
            endDate = dayjs().format('YYYY-MM-DD'),
            warehouseId = props.selectedWarehouse,
            queryStatus = '',
            queryExtOrderNumber = '',
            queryContact = '',
            queryExtractKey = '',
        } = getQuery(props.history)
        this.state = {
            startDate,
            endDate,
            warehouseId,
            queryStatus,
            queryExtOrderNumber,
            queryContact,
            queryExtractKey,
        }

        this.tableRef = React.createRef()
        this.orderDeliverModalRef = React.createRef()
        this.deliverOrderDetailRef = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)

        this.paginationInfo = {}
        this.columns = [{
            dataIndex: 'contact',
            key: 'contact',
            width: '10%',
            render: text => text.includes('/') ? (
                <>
                    <div className="text-center">
                        {text.split('/')[0]}
                    </div>
                    <div className="text-center">
                        {text.split('/')[1]}
                    </div>
                </>
            ) : (text || '--')
        }, {
            dataIndex: 'status',
            key: 'status',
            width: '10%',
            render: (text, record) => {
                let statusStr = WAREHOUSE_ORDER_STATUS[text] || '--'
                if (record.storage_status) {
                    return (
                        <>
                            <div className="text-center">{statusStr}</div>
                            <div className="text-center clr-orange">(部分商品库存不足)</div>
                        </>
                    )
                }
                return statusStr
            }
        }, {
            dataIndex: 'total',
            key: 'total',
            width: '10%',
            render: (text, record) => `￥${priceFenToYuan(text)}`
        }, {
            dataIndex: 'status',
            key: 'operation',
            width: '160px',
            render: (text, record) => this.renderListOperation(record)
        }]
        this.titleLineRender = data => (
            <>
                <span>订单编号：{data.order_number}</span>
                <span>下单时间：{data.submit_time}</span>
            </>
        )

    }

    handleValueChange(key, value) {
        if (key === 'dateRange') {
            this.setState({
                ...value
            }, this.initTable)
            return;
        }
        this.setState({
            [key]: value
        }, this.initTable)
    }

    goOrderDetail = ({ order_number }) => {
        const { history } = this.props
        const { warehouseId } = this.state
        history.push(`/warehouse/order/${warehouseId}/${order_number}/detail`)
    }

    orderDeliver(record) {
        const { getWarehouseOrderInfo } = this.props
        const { warehouseId } = this.state
        getWarehouseOrderInfo({
            id:warehouseId,
            orderNumber: record.order_number
        },(res)=>{
            this.orderDeliverModalRef.current?.show(res)
        })
    }

    orderReady(record) {
        const { creatWarehouseOrderReady } = this.props
        const { warehouseId } = this.state
        creatWarehouseOrderReady({
            id:warehouseId,
            orderNumber: record.order_number
        },()=>{
            notify('备货完成', 'success')
            this.getTableInfo()
        })
    }

    orderPickUp(record) {
        const {  creatWarehouseOrderPickUp } = this.props
        const { warehouseId } = this.state
        creatWarehouseOrderPickUp({
            id:warehouseId,
            orderNumber: record.order_number
        },()=>{
            notify('取货完成', 'success')
            this.getTableInfo()
        })
    }

    missNotify=(record)=>{
        const { creatWarehouseOrderMiss } = this.props
        const { warehouseId } = this.state
        creatWarehouseOrderMiss({
            id: warehouseId,
            orderNumber: record.order_number
        },()=>{
            notify('通知成功', 'success')
        })
    }

    renderListOperation(record)  {
        const commonOperation = (
            <React.Fragment>
                    <a className='mgr-24' onClick={this.goOrderDetail.bind(this, record)}>详情</a>
                    { record.status !== 99 ? (
                        <a className="row-modify-button"
                        onClick={() => this.deliverOrderDetailRef.current?.show({
                            orderNumber: record.order_number,
                            id: this.state.warehouseId
                        })}
                        >打印</a>
                    ) : null }
            </React.Fragment>
        )
        switch(record.status) {
            // 10 待备货
            case 10:
                return (
                    <div className="flex-row-right">
                        <DoubleCheck title='确定备货完成？' onClick={this.orderReady.bind(this,record)}>
                            <Button type="primary" ghost className="button-in-table mgr-24">备货</Button>
                        </DoubleCheck>
                        { commonOperation }
                    </div>
                )
            // 11 待自提
            case 11:
                return (
                    <div className="flex-row-right">
                        <DoubleCheck title='是否确认取货？' onClick={this.orderPickUp.bind(this,record)}>
                            <Button type="primary" ghost className="button-in-table mgr-24">取货</Button>
                        </DoubleCheck>
                        { commonOperation }
                    </div>
                )
            // 20 待发货 
            case 20:
                return (
                    <div className="flex-row-right">
                        {record.storage_status ? 
                            <DoubleCheck title='确定通知？' onClick={this.missNotify.bind(this,record)}>
                                  <Button type="primary" ghost className="button-in-table mgr-24">缺货通知</Button>
                            </DoubleCheck>
                         : null}
                        <Button type="primary" ghost className="button-in-table mgr-24" onClick={this.orderDeliver.bind(this,record)}>发货</Button>
                        { commonOperation }
                    </div>
                )
            default:
                return (
                    <div className='flex-row-right'>
                        { commonOperation }
                    </div>
                )
        }
    }

    getTableInfo({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { startDate, endDate, queryStatus, queryExtOrderNumber, queryContact, queryExtractKey, warehouseId } = this.state
        warehouseId && this.props.getWarehouseOrderProcess({
            id: warehouseId,
            startDate,
            endDate,
            queryStatus,
            queryExtOrderNumber,
            queryContact,
            queryExtractKey,
            pageNo: current,
            pageSize,
        })
        this.setUrlQuery()
    }

    initTable() {
        this.tableRef.current?.initPage()
    }

    setUrlQuery() {
        const { current, pageSize } = this.paginationInfo
        const { startDate, endDate, queryStatus, queryExtOrderNumber, queryContact, queryExtractKey, warehouseId } = this.state
        const { history } = this.props
        let params = {
            startDate, endDate,
            queryStatus,
            queryExtOrderNumber,
            queryContact,
            queryExtractKey, warehouseId, current, pageSize
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    render() {
        const { processOrderListMap } = this.props
        const { startDate, endDate, queryStatus, queryExtOrderNumber, queryContact, queryExtractKey, warehouseId, } = this.state
        return (
            <div className="table-scroll-container warehouse-order-page warehouse-order-list-page">
                <div className="table-params page-params flex-vertical-center mgb-16">
                    <WarehouseSelect 
                        value={warehouseId}
                        onChange={this.handleValueChange.bind(this, 'warehouseId')}
                    />
                    <DateRangePicker
                        className="mgl-16"
                        startDate={startDate}
                        endDate={endDate}
                        onChange={this.handleValueChange.bind(this, 'dateRange')}
                        beforeNow
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{ width: '140px' }}
                        value={queryContact}
                        onChange={this.handleValueChange.bind(this, 'queryContact')}
                        placeholder="下单人/手机号"
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{ width: '140px' }}
                        value={queryExtOrderNumber}
                        onChange={this.handleValueChange.bind(this, 'queryExtOrderNumber')}
                        placeholder="订单编号"
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{ width: '140px' }}
                        value={queryExtractKey}
                        onChange={this.handleValueChange.bind(this, 'queryExtractKey')}
                        placeholder="取货码"
                    />
                    <Tabs
                        activeKey={queryStatus}
                        className='tabs-status mgt-8'
                        onChange={this.handleValueChange.bind(this, 'queryStatus')}
                    >
                        {WAREHOUSE_ORDER_STATUS_LIST.map(orderStatus => (
                            <Tabs.TabPane tab={orderStatus.name} key={orderStatus.id} />
                        ))}
                    </Tabs>
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="warehouseOrderList" onChange={this.getTableInfo}>
                    <div className="table-list">
                        <CustomizeOrderTable
                            columns={this.columns}
                            dataSource={processOrderListMap.orders || []}
                            pagination
                            titleLineRender={this.titleLineRender}
                            productListKey=""
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={processOrderListMap.total}
                        />
                    </div>
                </CustomizeTableProvide>
                <OrderDeliverModal
                    id={warehouseId}
                    ref={this.orderDeliverModalRef}
                    callback={this.getTableInfo}
                />
                <DeliverOrderDetailModal
                    ref={this.deliverOrderDetailRef}
                    callback={this.getTableInfo}
                />
            </div>
        )
    }
}

export default WarehouseOrderPage